// pages/order_confirm/order_confirm.js
var common = require("../../common/common.js").common;

var app = getApp();

Page({
    /**
    * 页面的初始数据
    */
    data: {
        imageUrl: "",
        order_no: "",
        data: "",
        buy_goods: [],
        otherGoods: [],
        alert: 0,
        details: [],
        price: "",
        sku: "",
        buy_count: 1,
        sku_info: "",
        showDiscount: 0,
        lucky_member: "",
        status: "",
        little_title: "",
        cart_count: 0,
        awardBox: 0,
        awardList: [],
        integ: 0,
        balance: 0,
        shai: 0
    },
    /**
    * 生命周期函数--监听页面加载
    */
    onLoad: function(options) {
        this.getBase();
        this.setData({
            order_no: options.order_no,
            order_id: options.order_id,
            shai: options.shai || 0,
            domain: app.globalData.domain.slice(0, -10)
        });
        if (app.globalData.user) {
            //如果直接拿到openid
            this.setData({
                openid: app.globalData.user.openid,
                uid: app.globalData.user.uid
            });
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                this.setData({
                    openid: res.openid,
                    uid: res.uid
                });
            });
        }
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
    },
    /**
    * 生命周期函数--监听页面初次渲染完成
    */
    onReady: function() {},
    /**
    * 生命周期函数--监听页面显示
    */
    onShow: function() {
        common.getCart();
    },
    /**
    * 生命周期函数--监听页面隐藏
    */
    onHide: function() {},
    /**
    * 生命周期函数--监听页面卸载
    */
    onUnload: function() {},
    /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
    onPullDownRefresh: function() {},
    /**
    * 页面上拉触底事件的处理函数
    */
    onReachBottom: function() {},
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    luck_img: res.extra.luck_img,
                    little_title: res.extra.title,
                    order_jump: res.extra.order_jump ? res.extra.order_jump : "1",
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长"
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                that.getData();
            }
        });
    },
    /**
    * 用户点击右上角分享
    */
    onShareAppMessage: function(e) {
        var that = this;
        var status = e.target ? e.target.dataset.status : 1;
        var little_title = that.data.little_title;
        var lucky_member = that.data.lucky_member;
        var openid = wx.getStorageSync("user").openid;
        if (status == 1) {
            let pathUrl;
            if (that.data.data.channel == 0) {
                pathUrl = that.data.order_jump == 1 ? "/pagesOrder/pages/order_chain/order_chain?order_id=" + that.data.data.order_id + "&openid=" + openid + "&uid=" + that.data.uid : "/pages/index/index?uid=" + that.data.uid;
            } else {
                pathUrl = "/pages/index/index?uid=" + that.data.uid;
            }
            return {
                title: that.data.data.img_order_title,
                path: pathUrl
            };
        } else {
            var order_id = that.data.order_no;
            return {
                title: little_title + "拼手气，第" + lucky_member + "个人领取的红包最大！",
                path: `/pages/lucky_discount/lucky_discount?order_id=${order_id}&s_uid=${that.data.uid}`,
                imageUrl: that.data.luck_img
            };
        }
    },
    awardCreate: function() {
        var that = this;
        common.request({
            endpoint: "Award/award/create",
            method: "post",
            data: {
                order_id: that.data.data.order_id
            },
            success: res => {
                let awardBox = 0;
                if (Object.prototype.toString.call(res.extra) === "[object Object]") {
                    if (res.extra.voucher.length || res.extra.integ != 0 || res.extra.balance != 0) {
                        awardBox = 1;
                    }
                    that.setData({
                        awardBox: awardBox,
                        awardList: res.extra.voucher,
                        activity_id: res.extra.id,
                        integ: res.extra.integ,
                        balance: res.extra.balance
                    });
                }
            }
        });
    },
    receive_label: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        common.request({
            endpoint: "Award/award/draw",
            method: "post",
            data: {
                activity_id: id
            },
            success: res => {
                wx.showToast({
                    title: "领取成功"
                });
                that.setData({
                    awardBox: 0
                });
            },
            fail(err) {
                that.setData({
                    awardBox: 0
                });
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    showCancel: false
                });
            }
        });
    },
    close_award: function() {
        this.setData({
            awardBox: 0
        });
    },
    getData: function() {
        var that = this;
        var order_num = that.data.order_no;
        common.request({
            endpoint: "order/order_end",
            method: "post",
            data: {
                order_num: order_num
            },
            success: res => {
                that.setData({
                    data: res.extra,
                    buy_goods: res.extra.pro
                });
                that.awardCreate();
                that.discountOpen();
                that.getDetection();
            }
        });
    },
    getDetection: function() {
        common.request({
            endpoint: "Random/manage/detection",
            method: "post",
            data: {
                order_id: this.data.data.order_id
            },
            success: res => {
                var d = res.extra;
                if (d.status == 1 && this.data.shai == 0) {
                    var bill_id = d.bill_id;
                    wx.navigateTo({
                        url: `/random/pages/center/center?id=${bill_id}`
                    });
                }
            }
        });
    },
    close_alert: function(e) {
        this.setData({
            alert: 0
        });
    },
    join_cart: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        common.request({
            endpoint: "product/shopping-push",
            method: "post",
            data: {
                id: id
            },
            success: res => {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                that.setData({
                    details: details,
                    sku: sku,
                    alert: 1,
                    product_id: id,
                    sku_info: sku_info,
                    proId: id,
                    buy_count: 1
                });
            }
        });
    },
    /** 
    * 添加 sku 属性
    */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
    * 重平衡 sku
    * key_id: integer
    */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
    * 重建 sku
    */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
    * 对选择的 sku 属性进行排序
    */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
    * 分割现有 sku 成对象数组
    */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
    * 添加一个 sku
    */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
    * 选择 sku
    */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
    * 选择单个 sku 属性
    */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    save_count: function(e) {
        this.setData({
            buy_count: parseInt(e.detail.value)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let restrictions = e.currentTarget.dataset.restrictions;
        let buy_count = this.data.buy_count;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    /**
    * 根据 sku 获取物品
    */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    contactShop: function() {
        wx.makePhoneCall({
            phoneNumber: this.data.phone
        });
    },
    buy: function() {
        var that = this;
        var alert = that.data.alert;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.goodsId;
        var sku_id = sku_info.item_id;
        let sku_item = sku_info.item_id + "," + buy_count;
        if (sku_info.stock_number >= buy_count) {
            wx.navigateTo({
                url: "/newPlace_order/pages/newPlace_order/newPlace_order?sku_item=" + sku_item + "&status=" + 0
            });
            that.setData({
                alert: 0
            });
        } else {
            wx.showToast({
                title: "库存不足",
                icon: "none"
            });
            that.setData({
                alert: 0
            });
        }
    },
    join_goods: function() {
        var that = this;
        var alert = that.data.alert;
        var cart_count = wx.getStorageSync("cart_count") || 0;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var id = that.data.product_id;
        cart_count = cart_count + buy_count;
        var cart = wx.getStorageSync("cart") || [];
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= buy_count) {
                if (cart == "") {
                    let goods = {
                        id: sku_info.item_id,
                        product_id: id,
                        img: details.icon_img,
                        title: details.name,
                        varieties: sku_info.title,
                        price: sku_info.price,
                        o_price: sku_info.o_price,
                        count: buy_count,
                        stock_number: sku_info.stock_number,
                        select: 1,
                        proID: id,
                        status: 1
                    };
                    wx.showToast({
                        title: "加入购物车成功",
                        icon: "success",
                        success: res => {
                            wx.setStorage({
                                key: "cart_count",
                                data: cart_count
                            });
                            this.setData({
                                cart_count: cart_count
                            });
                            var cart = wx.getStorageSync("cart") || that.data.cart;
                            if (!cart) {
                                cart = [];
                            }
                            setTimeout(() => {
                                cart.push(goods);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                that.setData({
                                    buy_count: 1,
                                    alert: 0
                                });
                            }, 500);
                        }
                    });
                } else {
                    var total = 0;
                    var index = 0;
                    for (var i = 0; i < cart.length; i++) {
                        if (sku_info.item_id != cart[i]["id"]) {
                            total++;
                        } else {
                            index = i;
                            break;
                        }
                    }
                    if (total == cart.length) {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1
                        };
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "success",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                setTimeout(() => {
                                    var cart = wx.getStorageSync("cart") || that.data.cart;
                                    cart.push(goods);
                                    wx.setStorage({
                                        key: "cart",
                                        data: cart
                                    });
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0
                                    });
                                }, 500);
                            }
                        });
                    } else {
                        cart[index]["count"] = cart[index]["count"] + buy_count;
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "success",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                setTimeout(() => {
                                    wx.setStorage({
                                        key: "cart",
                                        data: cart
                                    });
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0
                                    });
                                }, 500);
                            }
                        });
                    }
                }
            } else {
                wx.showToast({
                    title: "加入购物车失败",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    showDiscount: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var order_id = that.data.order_no;
        common.request({
            endpoint: "Voucher/luckyvou/sendvoucher",
            method: "post",
            data: {
                order_id: order_id,
                openid: openid
            },
            success: res => {
                that.setData({
                    lucky_member: res.extra.lucky_member,
                    showDiscount: 1
                });
            }
        });
    },
    getDiscount: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var order_id = that.data.order_no;
        common.request({
            endpoint: "Voucher/luckyvou/sendvoucher",
            method: "post",
            data: {
                order_id: order_id,
                openid: openid
            },
            success: res => {
                that.setData({
                    lucky_member: res.extra.lucky_member,
                    showDiscount: 1
                });
            }
        });
    },
    closeDiscount: function() {
        this.setData({
            showDiscount: 0
        });
    },
    discountOpen: function() {
        var that = this;
        common.request({
            endpoint: "Voucher/luckyvou/isoff",
            method: "post",
            success: res => {
                that.setData({
                    status: res.extra.status
                });
                if (res.extra.status == 1) {
                    that.showDiscount();
                }
            }
        });
    },
    awardBox: function() {
        let that = this;
        that.setData({
            awardBox: 0
        });
    },
    showDiscountModal: function() {
        let that = this;
        that.setData({
            showDiscount: 1
        });
    }
});